package com.wck.car.car;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wck.car.car.service.AppCarFctService;
import com.wck.car.car.service.AppCarSeriesService;
import com.wck.car.model.AppCarFct;
import com.wck.car.model.AppCarSeries;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

@Component
public class CarPipeline implements Pipeline {

    @Resource
    private AppCarFctService carFctService;

    @Resource
    private AppCarSeriesService seriesService;

    @Autowired
    private CarTypePipeline carTypePipeline;

    @Override
    public void process(ResultItems resultItems, Task task) {
        String str = resultItems.get("repo");
        JSONObject jsonObject = (JSONObject) JSON.parseObject(str).get("result");
        String brandId = jsonObject.getString("brandid");
        String string = jsonObject.getString("fctlist");
        JSONArray jsonArray = JSONArray.parseArray(string);
        List<CarFct> list = (List<CarFct>) JSONArray.parseArray(string, CarFct.class);

        list.forEach(bean -> {
            //防止插入重复数据
            AppCarFct appCarFct = Optional.ofNullable(carFctService.getOne(new LambdaQueryWrapper<AppCarFct>()
                    .eq(AppCarFct::getBrandid, Integer.parseInt(brandId))
                    .eq(AppCarFct::getFctname, bean.getFctname()))).orElse(new AppCarFct());
            //插入车系
            bean.setBrandid(Integer.parseInt(brandId));
            BeanUtils.copyProperties(bean, appCarFct);
            appCarFct.setFctId(bean.getFctid());
            carFctService.saveOrUpdate(appCarFct);

            //插入车系详情
            bean.getSerieslist().forEach(carSeries -> {
                carSeries.setFctId(bean.getFctid());
                contextLoads3(carSeries.getSeriesid().toString());
                if (seriesService.count(new LambdaQueryWrapper<AppCarSeries>().eq(AppCarSeries::getSeriesName, carSeries.getSeriesName())) < 1) {
                    AppCarSeries series = new AppCarSeries();
                    BeanUtils.copyProperties(carSeries, series);
                    series.setState(carSeries.getSeriesState());
                    series.setSeriesId(appCarFct.getId());
                    seriesService.save(series);
                }
            });
        });
    }


    /**
     *  爬取车系款式年份
     */
    public void contextLoads3(String id) {
        Spider spider = Spider.create(new GithubRepoPageProcessor());
        spider.addPipeline(carTypePipeline);
        spider.addUrl("https://www.autohome.com.cn/ashx/index/GetHomeFindCar.ashx?type=2&seriesid=" + id + "&format=json&v=1");
        spider.thread(1);
        spider.setExitWhenComplete(true);
        spider.run();
        spider.stop();
    }
}
